package com.whmnx.main.ui.model;

import android.app.Application;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.alibaba.android.arouter.launcher.ARouter;
import com.whmnx.base.bean.ProductBean;
import com.whmnx.base.bean.TreeBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterFragmentPath;
import com.whmnx.base.utils.UItils;
import com.whmnx.base.view.CustomPopWindow;
import com.whmnx.main.BR;
import com.whmnx.main.R;
import com.whmnx.main.databinding.FragmentManagementBinding;
import com.whmnx.main.ui.fragment.AddCommodityFragment;
import com.whmnx.main.ui.fragment.CommodityClassifyFragment;
import com.whmnx.main.ui.fragment.MyManagementFragment;
import com.whmnx.main.ui.fragment.SetupRulesFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/9/27 0027 14:19
 * version: 1.0
 * @author Administrator
 */
public class ManagementModel extends ToolbarViewMainModel{
    //默认为像素值px
    private int pWidth;
    private int pwHeight;
    private PopupWindow window;
    public MyManagementFragment mActivity;
    private FragmentManagementBinding mBinding;
    private CustomPopWindow mPopupWindow;

    private android.widget.ListView listView;

    String objects[] = {"普通商品", "拼团商品", "全部商品"};
    String objects2[] = {"上架", "下架", "全部"};

    //给RecyclerView添加ObservableList
    public ObservableList observableList = new ObservableArrayList<>();

    private List<String> list = new ArrayList<>();

    private List<TreeBean> resultList;
    private String key;
    private  Disposable subscribe;
    private View contentView;
    private ListView rvList;
    private int type;
    private int pinPos,pinPos2;
    private boolean flag;
    private String price;

    private int page = 1;
    private int pageSize = 10;


    public ManagementModel(@NonNull Application application) {
        super(application);
    }

    public void initToolbar(MyManagementFragment myManagementFragment, FragmentManagementBinding binding) {
        setTitleText("商品管理");
        setRightText("分类管理");
        setRightTextVisible(View.VISIBLE);
        this.mActivity = myManagementFragment;
        this.mBinding = binding;
        initList();
        getProductmanager(true,"",2,"asc",2);
        initView();

    }

    private void initView() {
            subscribe = RxBus.getDefault().toObservable(String.class)
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String object){
                          if (object.equals(EventConstants.ADD)){
                              getProductmanager(true,"",2,"asc",2);
                            }else if (object.equals(EventConstants.ADD2)){
                              initList();
                          }
                            //解除注册
                          //  RxSubscriptions.remove(subscribe);
                        }
                    });
            RxSubscriptions.add(subscribe);

        mBinding.refresh.setOnRefreshListener(refreshLayout -> getProductmanager(true,"",2,"asc",2));
        mBinding.refresh.setOnLoadMoreListener(refreshLayout -> getProductmanager(false,"",2,"asc",2));
    }

    //商品管理
    public void getProductmanager(boolean isRefresh,String cId,int type,String sortOrder,int status) {
        if (isRefresh) page = 1;
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex",page);
        params.put("pageSize",pageSize);
        params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
        //2 是全部  类型(0:商品;1:拼团;2:全部;)
        params.put("type",type);
        //状态(0:上架;1:下架;2:全部;)
        params.put("status",status);
        //(正序：asc；倒序：desc)
        params.put("sortOrder",sortOrder);
        //分类id
        params.put("cId",cId);

        HttpClient.post(mActivity, Constants.PRODUCTMANAGER, params,new CallBack<List<ProductBean>>() {
            @Override
            public void onSuccess(List<ProductBean> productBeans) {
                if (isRefresh){
                    observableList.clear();
                    for (ProductBean productBean : productBeans) {
                        observableList.add(new ManagementItemViewModel(ManagementModel.this,productBean));
                    }
                    mBinding.refresh.finishRefresh(true);
                }else {
                    if (productBeans.size() > 0) {
                        for (ProductBean productBean : productBeans) {
                            observableList.add(new ManagementItemViewModel(ManagementModel.this,productBean));
                        }
                        mBinding.refresh.finishLoadMore(true);
                    } else {
                        mBinding.refresh.finishLoadMoreWithNoMoreData();
                    }
                }
                page++;
            }
        });
    }

    private void initList() {
        Map<String, Object> params = new HashMap<>();
        params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
        HttpClient.get(mActivity, Constants.GETCATEGORYTREE, params,new CallBack<List<TreeBean>>() {
            @Override
            public void onSuccess(List<TreeBean> result) {
                list.clear();
                resultList = result;
                for (TreeBean treeBean : result) {
                     list.add(treeBean.getTitle());
                }
            }
        });


        contentView = LayoutInflater.from(mActivity).inflate(R.layout.popwindow_view, null);
        rvList = contentView.findViewById(R.id.rv_list);

     //   listView.setBackground(ContextCompat.getDrawable(mActivity.getActivity(), R.drawable.gray_drawable_bg));
        //设置listview的点击事件
        rvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                if (type == 1){
                    key = resultList.get(position).getKey();
                    String title = resultList.get(position).getTitle();
                    mBinding.tvAll.setText(title);
                }else if (type == 2){
                    mBinding.tvPing.setText(objects[position]);
                    pinPos = position;
                }else if (type == 4){
                    mBinding.tvShang.setText(objects2[position]);
                    pinPos2 = position;
                }

                getProductmanager(true,key,pinPos,price,pinPos2);
                mPopupWindow.dissmiss();
            }
        });
    }



    //给RecyclerView添加ItemBinding
    public ItemBinding<ManagementItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_manage);

    //返回
    public BindingCommand backOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
          finish();
        }
    });
    //分类管理
    public BindingCommand rightTextOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(CommodityClassifyFragment.class.getCanonicalName());
        }
    });


    //添加商品
    public BindingCommand OnClickCommand1 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(AddCommodityFragment.class);
        }
    });


    //设置规则
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SetupRulesFragment.class.getCanonicalName());
        }
    });
    //商品操作说明
    public BindingCommand OnClickCommand0 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            SPUtils.getInstance().put("code", 3);
            ARouter.getInstance().build(RouterFragmentPath.User.MY_GUANLI).navigation();
        }
    });
    //拼团
    public BindingCommand OnClickCommand3 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ArrayAdapter<String> adapter = new ArrayAdapter(mActivity, R.layout.item_array,objects);
            rvList.setAdapter(adapter);
            showPopWindow(mBinding.tvPing);
            type = 2;
        }
    });
    //价格
    public BindingCommand OnClickCommand4 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (!flag){
                price = "desc";
                flag = true;
            }else {
                 price = "asc";
                 flag = false;
            }
            getProductmanager(true,key,pinPos,price,pinPos2);
            type = 3;
        }
    });
    //上架
    public BindingCommand OnClickCommand5 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ArrayAdapter<String> adapter = new ArrayAdapter(mActivity, R.layout.item_array,objects2);
            rvList.setAdapter(adapter);
            showPopWindow(mBinding.tvShang);
        //    getProductmanager(true,key,pinPos,price,pinPos2);
            type = 4;
        }
    });


    //全部商品
    public BindingCommand allOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ArrayAdapter<String> adapter = new ArrayAdapter(mActivity, R.layout.item_array,list);
            rvList.setAdapter(adapter);
            showPopWindow(mBinding.tvAll);
            type = 1;
        }
    });

    private void showPopWindow(TextView tvAll) {
        pWidth = mBinding.tvAll.getWidth();
        int popWidth = (int) (UItils.getDeviceDensity(mActivity).widthPixels) / 4;
        int popWindowHeight = (int) (UItils.getDeviceDensity(mActivity).heightPixels);
        mPopupWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .size(pWidth, popWindowHeight)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .enableBackgroundDark(false)
                .setBgDarkAlpha((float) 1)
                .create();
        mPopupWindow.showAsDropDown(tvAll, 0, 15);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(subscribe);
    }
}
